<template>
  <div class="market_pointshop_goods_create">
    <Form inline ref="formValidate" :rules="ruleValidate" :model="formData" :label-width="130">
      <Row>
        <FormItem label="所属模块：" prop="moduleType">
          <Select class="select-shop-item" v-model="formData.moduleType" :max-tag-count="1" style="width: 260px">
            <Option v-for="(item, index) in moduleType" :key="index" :value="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
      </Row>
      <Row>
        <FormItem class="from-table" prop="refId" label="优惠券：">
          <Table stripe :columns="columns" :data="tableData"></Table>
          <i @click="handleCuopotAdd" style="font-size: 24px" class="iconsys iconadd" title="添加"></i>
          <i @click="handleCuopotDel" style="font-size: 24px" class="iconsys icondel" title="删除"></i>
        </FormItem>
      </Row>
      <Row type="flex" justify="space-between">
        <FormItem prop="refName" label="商品名称：">
          <!-- v-filterinput="{reg: regExp.special}" @on-keyup="filtterRefName" -->
          <Input
            v-filterinput="{ reg: regExp.special }"
            placeholder="请输入"
            :maxlength="15"
            v-model="formData.refName"
            class="input-wdith"
          ></Input>
        </FormItem>
        <FormItem label="兑换价(积分)：" prop="price">
          <!-- v-filterinput="{reg: regExp.special}"  @on-keyup="onKeyup"-->
          <Input
            placeholder="请输入"
            v-filterinput="{ reg: regExp.nan, type: 'integerNumber' }"
            :maxlength="7"
            v-model="formData.price"
            class="input-wdith"
          ></Input>
        </FormItem>
      </Row>

      <Row type="flex" justify="space-between">
        <FormItem prop="buyLimit" label="兑换限制：">
          <Select disabled class="select-shop-item" style="width: 260px" v-model="formData.buyLimit" :max-tag-count="1">
            <Option v-for="(item, index) in buyLimit" :key="index" :value="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="memberLevel" label="等级限制：">
          <Select style="width: 260px" class="select-shop-item" v-model="formData.memberLevel" :max-tag-count="1">
            <Option v-for="(item, index) in memberLevel" :key="index" :value="String(item.memberLevel)">{{
              item.memberLevelId ? 'V' + (item.memberLevel + '及以上') : item.memberLevelName
            }}</Option>
          </Select>
        </FormItem>
      </Row>
      <Row>
        <FormItem prop="note" style="width: 100%" label="温馨提示：">
          <!-- <Input
            v-model="formData.note"
            placeholder="请输入"
            type="textarea"
            :maxlength="100"
            :autosize="{ minRows: 2, maxRows: 5 }"
          ></Input> -->
          <wangeditor v-model="formData.note"></wangeditor>
        </FormItem>
      </Row>
      <FormItem
        v-show="formData.moduleType === 0"
        prop="imageUrl"
        label="上传图片："
        class="loadimg-form"
        style="width:830px;"
      >
        <Row type="flex" align="top">
          <Col>
            <Upload
              ref="upload"
              :format="['jpg', 'png']"
              :max-size="500"
              :on-success="handleSuccess"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              type="drag"
              :action="$config.uploadImg"
              :show-upload-list="false"
              style="display: inline-block;width:96px"
            >
              <img
                :src="formData.imageUrl ? formData.imageUrl : defaultUrl"
                style="display: inline-block;width:96px;height:96px;vertical-align: top;"
                alt
              />
            </Upload>
            <p v-if="formData.imageUrl" class="replace_tit" @click="delHeadImage">删除</p>
          </Col>
          <Col>
            <div style="width:132px;height:72px;line-height:18px;color: #464C5B;margin-left:16px">
              <p>支持格式：.jpg、.png</p>
              <!-- <p>规格：128*128px</p> -->
              <p>大小：&lt;500KB</p>
            </div>
          </Col>
        </Row>
      </FormItem>
      <Row>
        <FormItem>
          <Button type="primary" :disabled="commitDisebled" style="width: 100px" @click="handleCommit">确认</Button>
          <Button @click="handleGo" style="width: 100px; margin-left: 20px;">取消</Button>
        </FormItem>
      </Row>
    </Form>

    <!-- 优惠券对话框 -->
    <!-- <Modal @on-ok='handleOk'  v-model="couponModal" width="800" title="搜索">
      <Form inline>
        <FormItem :label-width="130" label="优惠券名称：">
          <Input placeholder="请输入" v-model="formData.price" class="input-wdith"></Input>
        </FormItem>
        <FormItem :label-width="130" label="类型：">
          <Input placeholder="请输入" v-model="formData.price" class="input-wdith"></Input>
        </FormItem>
        <FormItem label="">
          <Button type="primary" style="width: 100px" @click="handleCommit">查询</Button>
          <Button style="width: 100px; margin-left: 20px;">重置</Button>
        </FormItem>
      </Form>
      <Table
        highlight-row
        stripe
        @on-current-change="handleCouponCurrent"
        :columns="couponModalColumns"
        :data="couponModalTableData"
      ></Table>

    </Modal>-->
    <Drawer v-model="couponModal" title="优惠券" @on-close="handleCancle" :styles="styles" width="900">
      <Form inline>
        <FormItem :label-width="90" label="优惠券名称：">
          <Input
            v-filterinput="{ reg: regExp.special }"
            :maxlength="20"
            placeholder="请输入"
            v-model="drawerForm.couponName"
            class="input-wdith"
          ></Input>
        </FormItem>
        <FormItem :label-width="50" label="类型：">
          <Select
            class="select-shop-item"
            v-model="drawerForm.couponType"
            :max-tag-count="1"
            style="width:180px"
            @on-change="handleDrawerQuery"
          >
            <Option v-for="(item, index) in drawerOption" :key="index" :value="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label>
          <Button type="primary" style="width: 100px" @click="handleDrawerQuery">查询</Button>
          <Button style="width: 100px; margin-left: 20px;" @click="handleDrawerReset">重置</Button>
        </FormItem>
      </Form>
      <Table
        class="market_pointshop_goods_drawer-table"
        :max-height="550"
        highlight-row
        stripe
        @on-current-change="handleCouponCurrent"
        :columns="couponModalColumns"
        :data="couponModalTableData"
      ></Table>
      <Row class="page-box" style="margin-top: 20px">
        <Page
          :total="drawerTotal"
          ref="pages"
          :current.sync="drawerForm.pageIndex"
          :page-size="drawerForm.limit"
          @on-change="handlePage"
          @on-page-size-change="handlePageSize"
          show-sizer
          show-total
        />
      </Row>
      <Row
        type="flex"
        justify="end"
        class="bottom-form-item"
        style="width: 100%; padding: 20px 30px; border-top: 1px solid #e8eaec; position: absolute; right: 0; bottom: 0;"
      >
        <Col>
          <Button style="width: 80px" @click="handleCancle">取消</Button>
          <Button type="primary" style="margin-left: 20px; width: 80px" @click="handleOk">确定</Button>
        </Col>
      </Row>
    </Drawer>
    <!-- <drawer-coupon v-model="Dmodal" :data="[]" @sure="handleSelectCoupon" :maxsize="1"></drawer-coupon> -->
  </div>
</template>
<script>
import { couponList, couponDetail, shopUp } from '@/api/market/pointshop'
import { getMemberLevelList } from '@/api/member/index.js'
import DrawerCoupon from '@/view/components/drawer-coupon/index.vue'
import enumsMixin from '@/view/market/enums.js'
import regExp from '@/libs/regExp'
import { routeEqual } from '@/libs/util'
import wangeditor from '@/components/wangeditor'
const validatePrice = (rule, value, callback) => {
  if (!/^(-|\+)?\d+$/.test(value)) return callback(new Error('请输入数字'))
  if (value < 0) return callback(new Error('不能小于0'))
  callback()
}
export default {
  name: 'market_pointshop_goods_create',
  components: { DrawerCoupon, wangeditor },
  mixins: [enumsMixin],
  data () {
    return {
      defaultUrl: require('@/assets/images/add.png'),
      formData: {
        moduleType: 0,
        buyLimit: '', // 兑换限制
        refName: '', // 商品名称
        price: '', // 积分
        memberLevel: '', // 等级限制
        note: '', // 温馨提示
        imageUrl: '', // 图片
        refId: '', //
        refType: '', // 优惠券类型
        promotionAmount: ''
      },
      commitDisebled: false, // 防止重复提交
      tempImage: '', // 优惠券图片
      regExp: regExp,
      drawerOption: [
        { label: '全部', value: -1 },
        { label: '代金券', value: 0 },
        { label: '折扣券', value: 1 },
        { label: '赠币券', value: 2 },
        { label: '赠送积分', value: 3 },
        { label: '手动录入商品', value: 4 }
      ],
      // 表单
      drawerForm: {
        couponName: '',
        couponType: -1,
        offset: 0,
        limit: 10,
        pageIndex: 1
      },
      drawerTotal: 0,
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      detail: {}, // 详情数据
      couponModal: false,
      buyLimit: [
        { value: 0, label: '无限制' },
        { value: 1, label: '限制一次' }
      ],
      ruleValidate: {
        moduleType: [{ required: true, message: '请选择所属模块' }],
        refName: [{ required: true, message: '请输入商品名称' }],
        price: [{ required: true, message: '请输入兑换价' }, { validator: validatePrice }],
        buyLimit: [{ required: true, message: '请选择兑换限制' }],
        memberLevel: [{ required: true, message: '请选择等级限制' }],
        note: [
          { required: true, message: '请输入温馨提示', trigger: 'blur' },
          { type: 'string', max: 2000, message: '最多只能输入2000', trigger: 'blur' }
        ],
        imageUrl: [{ required: true, message: '请添加图片' }],
        refId: [{ required: true, message: '请选择优惠券' }]
      },
      memberLevel: [{ memberLevelName: '无限制', memberLevel: -1 }],
      // moduleType: [
      //   // 0 hot专区 1 积分兑好礼 2 等级进阶礼
      //   { value: 0, label: 'hot专区' },
      //   { value: 1, label: '积分兑好礼' },
      //   { value: 2, label: '等级进阶礼' }
      // ],
      columns: [
        { title: '优惠券名称', key: 'couponName', align: 'center' },
        {
          title: '类型',
          key: 'couponType',
          align: 'center',
          render: (h, params) => {
            return h('span', ['代金券', '折扣券', '赠币券', '赠送积分', '手动录入商品'][params.row.couponType])
          }
        },

        { title: '有效期', key: 'expirationLimit', align: 'center' },
        {
          title: '使用渠道',
          key: 'channel',
          align: 'center',
          render: (h, params) => {
            return h(
              'span',
              (row => {
                if (row.channel && row.channel.length) {
                  return row.channel
                    .map(item => {
                      return this.channelFilter[item]
                    })
                    .join(',')
                } else {
                  return ''
                }
              })(params.row)
            )
          }
        },
        {
          title: '最低使用金额(元)',
          key: 'accumAmount',
          align: 'center'
          // render: (h, params) => {
          //   return h('span', [' hot专区', '积分兑好礼', '等级进阶礼'][params.row.moduleType])
          // }
        }
      ],
      tableData: [],
      couponModalColumns: [
        {
          title: '选择',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            let cla = ['ivu-radio']
            if (params.row.couponId === this.couponModalTableSesect.couponId) {
              cla = ['ivu-radio', 'ivu-radio-checked']
            }
            return h(
              'span',
              {
                class: cla
              },
              [
                h('span', {
                  class: ['ivu-radio-inner']
                })
              ]
            )
          }
        },
        { title: '优惠券名称', key: 'couponName', align: 'center' },
        {
          title: '类型',
          key: 'couponType',
          align: 'center',
          render: (h, params) => {
            return h('span', ['代金券', '折扣券', '赠币券', '赠送积分', '手动录入商品'][params.row.couponType])
          }
        },
        { title: '有效期', key: 'expirationLimit', align: 'center' },
        {
          title: '使用渠道',
          key: 'channel',
          align: 'center',
          render: (h, params) => {
            return h(
              'span',
              (row => {
                if (row.channel && row.channel.length) {
                  return row.channel
                    .map(item => {
                      return this.channelFilter[item]
                    })
                    .join(',')
                } else {
                  return ''
                }
              })(params.row)
            )
          }
        },
        { title: '最低使用金额(元)', key: 'accumAmount', align: 'center' }
      ],
      couponModalTableData: [],
      couponModalTableSesect: {}
    }
  },
  computed: {
    channelFilter () {
      let obj = {}
      this.channelList.forEach(item => {
        Reflect.set(obj, item.value, item.label)
      })
      return obj
    }
  },
  created () {
    this.getMemberLevelList()
  },
  watch: {
    'formData.moduleType': {
      handler: function (val) {
        if (val === 2) {
          this.formData.buyLimit = 1
        } else {
          this.formData.buyLimit = 0
        }
        if (val !== 0) {
          // this.ruleValidate.imageUrl =  [{ required: false, message: '请添加图片' }]
          this.$set(this.ruleValidate, 'imageUrl', [{ required: false, message: '请添加图片' }])
        } else {
          this.$set(this.ruleValidate, 'imageUrl', [{ required: true, message: '请添加图片' }])
          //  this.ruleValidate.imageUrl =  [{ required: true, message: '请添加图片' }]
        }
      },
      immediate: true
    },
    tableData: {
      handler: function (val) {
        if (val.length) {
          // debugger promotionAmount
          this.formData.refId = val[0].couponId
          this.formData.refType = val[0].couponType
          this.formData.promotionAmount = val[0].promotionAmount
          this.tempImage = val[0].iconPath
        } else {
          this.formData.refId = ''
          this.formData.refType = ''
          this.tempImage = ''
        }
      },
      deep: true,
      immediate: true
    }
  },
  // beforeRouteLeave (to, from, next) {
  //   this.$store.commit('closeTag', this.$route)
  //   this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
  //   next()
  // },
  methods: {
    uploadSuccess () {},
    onKeyup (evt) {
      let val = this.formData.price && this.formData.price.replace(/\D/g, '')
      if (val === '') {
        this.formData.price = ''
      } else {
        this.formData.price = Number.parseFloat(val)
      }
    },
    filtterRefName () {
      this.formData.refName = this.formData.refName.replace(this.regExp.special, '')
    },
    handleSelectCoupon (val) {},
    async getMemberLevelList () {
      const res = await getMemberLevelList({ merchantId: this.$store.state.user.merchantId })
      if (res.data.status !== 200) return this.$Message.error(res.data.error)
      if (res.data && res.data.data) {
        this.memberLevel.push(...res.data.data)
      }
    },
    handleCancle () {
      // 取消弹窗
      this.drawerForm = {
        couponName: '',
        couponType: -1,
        offset: 0,
        limit: 10,
        pageIndex: 1
      }
      this.couponModal = false
      this.couponModalTableData = []
      this.couponModalTableSesect = this.tableData[0] || {}
    },
    // 查询
    handleDrawerQuery () {
      this.drawerForm = {
        ...this.drawerForm,
        offset: 0,
        limit: 10,
        pageIndex: 1
      }
      this.couponList()
    },
    // 重置
    handleDrawerReset () {
      this.drawerForm = {
        couponName: '',
        couponType: -1,
        offset: 0,
        limit: 10,
        pageIndex: 1
      }
      this.couponList()
    },
    // 确认
    handleCommit () {
      if (this.formData.moduleType === 0) {
      }
      let params = {
        ...this.formData,
        merchantId: this.$store.state.user.merchantId,
        // refId: this.tableData[0].couponId,
        mallLayoutId: this.$route.params.id,
        imageUrl: this.formData.moduleType === 0 ? this.formData.imageUrl : this.tempImage
        // channel: this.detail.channel,
      }
      this.$refs['formValidate'].validate(valid => {
        if (valid) {
          this.commitDisebled = true
          this.shopUp(params)
        }
      })
    },
    // 优惠添加
    handleCuopotAdd () {
      // this.Dmodal = true
      this.couponList()

      this.couponModal = true
    },
    // 优惠删除
    handleCuopotDel () {
      this.tableData = []
      this.couponModalTableSesect = []
    },
    // 删除图片
    delHeadImage () {
      this.formData.imageUrl = ''
    },
    // 图片上传成功
    handleSuccess (response, file, fileList) {
      this.formData.imageUrl = response.full_img_url
    },
    // 图片上传失败
    handleFormatError () {
      this.$Message.warning('上传的图片格式错误')
    },
    // 图片大小
    handleMaxSize () {
      this.$Message.warning('上传的图片大小不能超过500k')
    },
    handleCouponCurrent (val) {
      this.couponModalTableSesect = val
    },
    // 选择确定
    handleOk () {
      this.couponModal = false

      this.tableData = [this.couponModalTableSesect]
      this.couponModalTableData = []
      // this.couponModalTableSesect = this.tableData[0] || {}
    },
    // 优惠券列表
    async couponList () {
      const res = await couponList({
        ...this.drawerForm,
        merchantId: this.$store.state.user.merchantId,
        couponName: this.drawerForm.couponName,
        couponType: this.drawerForm.couponType === -1 ? '' : this.drawerForm.couponType,
        originType: 0
      })
      if (res.data.status !== 200) return this.$Message.error(res.data.error)
      if (res.data && res.data.data) {
        this.couponModalTableData = res.data.data
        this.drawerTotal = res.data.totalCount
      }
    },
    // 优惠券详情
    async couponDetail (refId) {
      const res = await couponDetail({ refId })
      if (res.data.status !== 200) return this.$Message.error(res.data.error)
      if (res.data && res.data.data) {
        this.tableData.push(Object.assign(res.data.data, { couponId: refId }))
      }
    },
    // 更新
    async shopUp (params) {
      const res = await shopUp(params)
      setTimeout(() => {
        this.commitDisebled = false
      }, 50)
      if (res.data.status !== 200) return this.$Message.error(res.data.error)
      if (res.data && res.data.status === 200) {
        this.$store.commit('closeTag', this.$route)
        this.$store.commit(
          'setTagNavList',
          this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item))
        )
        this.$Message.success('上架成功')
        this.$nextTick(() => {
          this.$router.push({
            name: 'market_pointshop_goods_list'
          })
        })
      }
    },
    handlePage (val) {
      this.drawerForm.offset = this.drawerForm.limit * (val - 1)
      this.couponList()
    },
    handlePageSize (val) {
      this.drawerForm.limit = val
      if (this.drawerForm.pageIndex === 1) {
        this.couponList()
      } else {
        this.drawerForm.pageIndex = 1
      }
    },
    handleGo () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit(
        'setTagNavList',
        this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item))
      )
      // this.$Message.success('上架成功')
      this.$nextTick(() => {
        this.$router.push({
          name: 'market_pointshop_goods_list'
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.market_pointshop_goods_create {
  width: 830px;
  margin: 0 auto;
  margin-top: 100px;
  .input-wdith {
    width: 260px;
  }
  .loadimg-form {
    // width: 850px;
  }
  .from-table {
    position: relative;
    i {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
    .icondel {
      right: -50px;
    }
    .iconadd {
      right: -80px;
      color: #2d8cf0;
    }
  }
  .replace_tit {
    position: absolute;
    left: 0;
    top: 72px;
    width: 96px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    opacity: 0.8;
    background: #ed4014;
    color: #fff;
  }
  .demo-drawer-footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
  }
}
</style>
<style lang="less">
.market_pointshop_goods_drawer-table {
  border-left: none;
  border-right: none;
  overflow: hidden !important;
  .ivu-table::after {
    content: '';
    width: 1px;
    height: 100%;
    position: absolute;
    top: 0;
    right: 0;
    background-color: #fff;
    z-index: 3;
  }
}
</style>
